package com.wantupai.mvp.framework.support.manager;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.ContextWrapper;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.util.ArrayMap;


import com.wantupai.mvp.mvp.MvpPresenter;
import com.wantupai.mvp.mvp.MvpView;

import java.util.Map;
import java.util.UUID;


/**
 * 备忘录里面->管理备忘录角色
 *
 * @author: zhangqing
 */
public class PresenterManager {
    private static final String KEY_ACTIVITY_ID = "cn.doolii.mvp.framework.support.manager.PresenterManager.PresenterManagerActivityId";
    //缓存集合->Map集合->缓存Activity->ID
    private final static Map<Activity, String> activityIdMap = new ArrayMap<Activity, String>();
    //缓存Activtiy
    private final static Map<String, ActivityScopeCache> activityScopeCacheMap = new ArrayMap<String, ActivityScopeCache>();

    //通过application监听activity的创建过程
    static final Application.ActivityLifecycleCallbacks activityLifecycleCallbacks = new Application.ActivityLifecycleCallbacks() {
        @Override
        public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
            if (savedInstanceState != null) {
                //需要进行缓存处理
                String activityId = savedInstanceState.getString(KEY_ACTIVITY_ID);
                if (activityId != null) {
                    //缓存
                    activityIdMap.put(activity, activityId);
                }
            }
        }

        @Override
        public void onActivityStarted(Activity activity) {

        }

        @Override
        public void onActivityResumed(Activity activity) {

        }

        @Override
        public void onActivityPaused(Activity activity) {

        }

        @Override
        public void onActivityStopped(Activity activity) {

        }

        @Override
        public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
            String activityId = activityIdMap.get(activity);
            if (activityId != null) {
                //缓存数据
                outState.putString(KEY_ACTIVITY_ID, activityId);
            }
        }

        @Override
        public void onActivityDestroyed(Activity activity) {
            //释放对象
            if (!activity.isChangingConfigurations()) {//说明activity需要被销毁对象
                String activityId = activityIdMap.get(activity);
                if (activityId != null) {//说明存在
                    //根据当前的activity获取对应的Presenter
                    ActivityScopeCache activityScopeCache = activityScopeCacheMap.get(activityId);
                    if (activityScopeCache != null) {
                        activityScopeCache.clear();
                        activityScopeCacheMap.remove(activityId);
                    }
                    if (activityScopeCacheMap.isEmpty()) {
                        //取消activity的监听
                        activity.getApplication().unregisterActivityLifecycleCallbacks(activityLifecycleCallbacks);
                    }
                }
            }
            activityIdMap.remove(activity);
        }
    };

    private PresenterManager() {
        throw new RuntimeException("运行时异常，这个类不允许被创建");
    }

    static ActivityScopeCache getOrCreateActivityScoprCache(Activity activity) {
        if (activity == null) {
            throw new NullPointerException("activity 不能为空");
        }
        String activityId = activityIdMap.get(activity);
        if (activityId == null) {
            activityId = UUID.randomUUID().toString();
            activityIdMap.put(activity, activityId);
            if (activityIdMap.size() == 1) {
                //注册activity的生命周期监听器
                activity.getApplication().registerActivityLifecycleCallbacks(activityLifecycleCallbacks);
            }
        }
        ActivityScopeCache activityScopeCache = activityScopeCacheMap.get(activity);
        if (activityScopeCache == null) {
            activityScopeCache = new ActivityScopeCache();
            activityScopeCacheMap.put(activityId, activityScopeCache);
        }
        return activityScopeCache;
    }

    //得到具体的presenter
    public static <P> P getPresenter(Activity activity, String viewId) {
        if (activity == null) {
            throw new NullPointerException("activity 不能为空!");
        }
        if (viewId == null) {
            throw new NullPointerException("viewId 不能为空");
        }
        ActivityScopeCache activityScopeCache = getOrCreateActivityScoprCache(activity);
        return activityScopeCache == null ? null : (P) activityScopeCache.getPresenter(viewId);
    }

    //得到Activity
    public static Activity getActivity(Context context) {
        if (context == null) {
            throw new NullPointerException("context不能为空!");
        }
        if (context instanceof Activity) {
            return (Activity) context;
        }
        while (context instanceof ContextWrapper) {
            if (context instanceof Activity) {
                return ((Activity) context);
            }
            context = ((ContextWrapper) context).getBaseContext();
        }
        throw new IllegalStateException("找不到Activity");
    }

    //重置管理器
    public static void resest() {
        activityIdMap.clear();
        for (ActivityScopeCache activityScopeCache : activityScopeCacheMap.values()) {
            activityScopeCache.clear();
        }
        activityScopeCacheMap.clear();
    }

    //添加presenter
    public static <V extends MvpView, P extends MvpPresenter<V>> void putPresenter(Activity mActivity, String viewId, P presenter) {
        if (mActivity == null) {
            throw new NullPointerException("activity不能为空");
        }
        ActivityScopeCache activityScopeCache = getOrCreateActivityScoprCache(mActivity);
        activityScopeCache.putPresenter(viewId, presenter);
    }

    //删除指定的P
    public static void remove(Activity mActivity, String viewId) {
        if (mActivity == null) {
            throw new NullPointerException("activity不能为空");
        }
        ActivityScopeCache activityScopeCache = getOrCreateActivityScoprCache(mActivity);
        if (activityScopeCache != null) {
            activityScopeCache.remove(viewId);
        }
    }


    /**********************备忘录模式->备份ViewState***************************************/

    public static <VS> VS getViewState(@NonNull Activity activity, @NonNull String viewId) {
        if (activity == null) {
            throw new NullPointerException("activity不能为空");
        }
        if (viewId == null) {
            throw new NullPointerException("viewId不能为空");
        }
        ActivityScopeCache activityScopeCache = getOrCreateActivityScoprCache(activity);
        return activityScopeCache == null ? null : ((VS) activityScopeCache.getViewState(viewId));
    }

    public static <VS> void putViewState(@NonNull Activity activity, @NonNull String viewId, @NonNull Object viewState) {
        if (activity == null) {
            throw new NullPointerException("activity不能为空");
        }
        if (viewId == null) {
            throw new NullPointerException("viewId不能为空");
        }
        ActivityScopeCache activityScoprCache = getOrCreateActivityScoprCache(activity);
        activityScoprCache.putViewState(viewId, viewState);
    }
}
